package com.my.test;

import static org.junit.Assert.*;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import org.junit.Test;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * 
 * 功能描述:java 代码生成测试
 *
 * @author: 李忠翔
 * @date： 2016年6月8日
 */
public class GeneratFile {
	@Test
	public void GenerateJava() throws Exception {
		Configuration cf = new Configuration();
		String path = this.getClass().getResource("/Template").getPath();
		System.out.println(path);
		cf.setDirectoryForTemplateLoading(new File(path));
		cf.setObjectWrapper(new DefaultObjectWrapper());
		
		Template template = cf.getTemplate("SwiftFieldClass.ftl","utf-8");
		
		/* Create a data-model */  
        Map<String, Object> root = new HashMap<String, Object>();  
        root.put("class", "F32B");  
        Collection<Map<String, String>> properties = new HashSet<Map<String, String>>();  
        root.put("properties", properties);  
  
        /* subfield 1: currency */  
        Map<String, String> currency = new HashMap<String, String>();  
        currency.put("name", "currency");  
        currency.put("type", "String");  
        properties.add(currency);  
  
        /* subfield 2: amount */  
        Map<String, String> amount = new HashMap<String, String>();  
        amount.put("name", "amount");  
        amount.put("type", "Double"); 
        properties.add(amount);  
        
        for (int i = 0; i < 100; i++) {
        	amount = new HashMap<String, String>();  
            amount.put("name", "amount"+i);  
            amount.put("type", "Double"); 
            properties.add(amount);
		}
        File file = new File(path+"/"+root.get("class")+".java");
        if(file.exists()){
        	file.delete();
        }
       // Writer out = new OutputStreamWriter(System.out);  
        OutputStream out = new FileOutputStream(path+"/"+root.get("class")+".java",true);  
        template.process(root, new BufferedWriter(new OutputStreamWriter(out,"utf-8")) ); 
        out.flush(); 
        out.close();
	}
}
